package edu.ec.java02.group02.controller;

import edu.ec.java02.group02.domain.UserInfo;
import edu.ec.java02.group02.service.ManagerService;
import edu.ec.java02.group02.util.ListSort;
import edu.ec.java02.group02.domain.*;
import edu.ec.java02.group02.service.UserService;
import edu.ec.java02.group02.util.Page;
import edu.ec.java02.group02.util.ResultMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private ManagerService managerService;



    @RequestMapping("/home")
    public String login(UserInfo userInfo){
        return "/home/home";
    }

    /**
     * 搜索商品
     * @param modelMap
     * @param searchInput
     * @return
     */
    @RequestMapping("/search")
    public String home1(ModelMap modelMap,String searchInput){
        System.out.println(searchInput);
        List<ProductInfo> list= userService.listProductInfo(searchInput);
        modelMap.addAttribute("list",list);
        return "front/protected/search";
    }
    @RequestMapping("/introduction")
    public String introduction(Model model, @RequestParam int productId){
        ProductInfo productInfo=userService.selectProductInfo(productId);
        model.addAttribute("product",productInfo);
        return "front/protected/introduction";
    }
    @RequestMapping("/pay")
    // num 为购买数量
    public  String pay(Model model,@RequestParam String productId,@RequestParam String num){
        String[] pid= productId.split(";");
        String[] n = num.split(";");
        System.out.println(n[0]);
        List<ProductInfo> pros=new ArrayList<ProductInfo>();
        for(int i =0 ;i<pid.length;i++){
            //这里用库存属性 寄存 购买数量
            ProductInfo p = new ProductInfo();
            p=userService.selectProductInfo(Integer.parseInt(pid[i]));
            p.setProductSaleAccount(Integer.parseInt(n[i]));
            pros.add(p);
        }

        model.addAttribute("product",pros);
        return "front/protected/pay";
    }
    @RequestMapping("/sort")
    public  String sort(){
        return "home/sort";
    }
    @RequestMapping("/success")
    public  String success(HttpServletRequest request,Model model,@RequestParam String ids,@RequestParam String nums,@RequestParam float total){
        String[] id = ids.split(";");
        String[] num = nums.split(";");
        UserInfo user = (UserInfo) request.getSession().getAttribute("login");

        for(int i=0;i<id.length;i++) {
            Cart cart = new Cart();
            cart.setProductId(Integer.parseInt(id[i]));
            cart.setProductNumber(Integer.parseInt(num[i]));
            cart.setUserId(user.getUserId());//---整合使用session登录用户的id
            if(!userService.buyProductFromCart(cart)){
                return "front/home";
            }
        }
        request.setAttribute("total",total);
        return "front/protected/success";

    }
    @RequestMapping("/bill")
    public  String bill(){
        return "person/bill";
    }
    @RequestMapping("/billlist")
    public  String billlist(){
        return "person/billlist";
    }


    @RequestMapping("/order")
    public  String order(HttpServletRequest request,Model model){
        List<Order> ls1 = new ArrayList<>();
        List<ProductInfo> prols = new ArrayList<>();
        UserInfo user = (UserInfo)request.getSession().getAttribute("login");
        List<OrderDetail> ls2=userService.findOrderDetailInfo(user.getUserId());//---整合使用session登录用户的id
        if(ls2.size()>0){
            for(OrderDetail orderDetail:ls2)
            {
                ls1.add(userService.findOrderInfo(orderDetail.getOrderNo()));
                prols.add(userService.selectProductInfo(orderDetail.getProductId()));
            }
            ListSort.removeDuplicateWithOrder(ls1);
            ListSort.removelist(prols);
            model.addAttribute("Product",prols);
            model.addAttribute("Order",ls1);
            model.addAttribute("OrderDetail",ls2);
            return "person/order";
        }
        return "person/order";
    }

    /**
     * 完成订单
     * @param id
     * @return
     */
    @RequestMapping("upOder1")
    public  String upOder1(@RequestParam int id){
        //System.out.println(id);
        Order order = userService.selectOrderKey(id);
        Date date=new Date(System.currentTimeMillis());
        order.setOrderFinishTime(date);
       if(userService.updateOrder(order))
        {
            return "redirect:/user/order";
        }
        return "redirect:/user/order";
    }

    /**
     * 取消订单
     * @param id
     * @return
     */
    @RequestMapping("upOder2")
    public  String upOder2(@RequestParam int id){
        //System.out.println(id);
        Order order = userService.selectOrderKey(id);
        Date date=new Date(System.currentTimeMillis());
        order.setOrderCancelTime(date);
        if(userService.updateOrder(order)){
           return "redirect:/user/order";
        }
        return  "redirect:/user/order";
    }
    /**
     * 进入用户管理界面
     * @param request
     * @return
     */
    @RequestMapping("/userList")
    public String userList(HttpServletRequest request){
        List<UserInfo> list = managerService.getUserList();
        request.setAttribute("Users",list);
        request.setAttribute("Total",list.size());
        return "user/user-list";
    }

    /**
     * 获取用户信息-分页
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/getUserPage")
    @ResponseBody
    public ResultMap<List<UserInfo>> getUserPage(Page page,int limit,HttpServletRequest request){
        page.setRows(limit);
        page.setUserName(request.getParameter("userName"));
        page.setUserState(request.getParameter("userState"));
        List<UserInfo> userInfoList = managerService.selectUserListPage(page);
        int totals = managerService.selectUserPageCount(page);
        page.setTotalRecord(totals);
        return new ResultMap<List<UserInfo>>("",userInfoList,0,totals);
    }

    /**
     * 进入添加用户界面
     * @return
     */
    @RequestMapping("addUserHtm")
    public String addUserHtm(){
        return "/user/user-add";
    }

    /**
     * 接收前台用户数据并传递给ManagerService进行事务处理
     * @param request
     * @return
     */
    @RequestMapping("addUser")
    public String addUser(HttpServletRequest request){
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(request.getParameter("userName"));
        userInfo.setUserPassword(request.getParameter("userPassword"));
        userInfo.setUserPhone(request.getParameter("userPhone"));
        userInfo.setReceiveAddress(request.getParameter("receiveAddress"));
        managerService.saveUserInfo(userInfo);
        return "/user/user-add";
    }

    /**
     * 进入修改用户界面
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping("updateUserHtm")
    public String updateUserHtm(String userId,HttpServletRequest request){
        UserInfo userInfo = managerService.getUserById(Integer.parseInt(userId));
        request.setAttribute("User",userInfo);
        return "/user/user-edit";
    }

    /**
     *修改用户信息
     * @param request
     * @return
     */
    @RequestMapping("updateUser")
    public String updateUser(HttpServletRequest request){
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Integer.parseInt(request.getParameter("userId")));
        userInfo.setUserName(request.getParameter("userName"));
        userInfo.setUserPassword(request.getParameter("userPassword"));
        userInfo.setUserPhone(request.getParameter("userPhone"));
        userInfo.setReceiveAddress(request.getParameter("receiveAddress"));
        managerService.modifyUserInfo(userInfo);
        return "/user/user-edit";
    }

    @RequestMapping("/ooo")
    public String oko(String str){
        return "front/protected/introduction";
    }

    /**
     * 修改用户状态(停用和启用)
     * @param userId
     * @param userState
     * @return
     */
    @RequestMapping("updateUserState")
    @ResponseBody
    public String updateUserState(String userId,String userState){
        return managerService.modifyUserStatus(Integer.parseInt(userId),userState);
    }

    /**
     * 删除用户信息(含多选删除)
     * @param userIds
     * @return
     */
    @RequestMapping("delUser")
    @ResponseBody
    public String delUser(String userIds){
        return managerService.deleteUserInfo(userIds);
    }


    //*******************************lqg's code*************************************//

    /**
     * 进入个人中心
     * @return
     */
    @RequestMapping("index")
    public String person(){
        return "person/index";
    }

    /**
     * 进入个人中心的个人信息页面
     * @return
     */
    @RequestMapping("/information")
    public  String information(){
        return "person/information";
    }

    /**
     * 进入个人中心的收货地址页面
     * @return
     */
    @RequestMapping("address")
    public String personAddress(){
        return "person/address";
    }

    /**
     * 修改用户信息
     * @param request
     * @param userName
     * @param userPhone
     * @return
     */
    @RequestMapping("changeUserInfo")
    public String changeUserInfo(HttpServletRequest request ,@RequestParam String userName,@RequestParam String userPhone){
        UserInfo user = (UserInfo)request.getSession().getAttribute("login");
        userService.changeUserInfo(user,userName,userPhone);
        return "person/information";
    }

    /**
     * 用户注册
     * @return
     */
    @RequestMapping("register")
    public String register(){
        return "front/register";
    }

    @RequestMapping("doRegister")
    public String doRegister(@RequestParam String userName,@RequestParam String password, @RequestParam String passwordRepeat){
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userName);
        userInfo.setUserPassword(password);
        userService.register(userInfo);
        return "/front/login";
    }
}
